<template>
  <el-form-item prop="optionItems" label="枚举值：">
    <el-input v-model="items" type="textarea" rows="4" @blur="getOptions" />
  </el-form-item>
</template>

<script lang="ts" setup>
import { useFormStore } from "@bis/stores/form";
import { ref, watch } from "vue";
import { isEmptyStr, splitTextByEnter } from "@bis/utils/utils";
import { ElMessage } from "element-plus";
import { editQue } from "../../../utils";

const formStore = useFormStore();

const items = ref("");

watch(
  () => formStore.selectQuestion.optionItems,
  () => {
    formStore.selectQuestion.optionItems && (items.value = getOptionsStr());
  },
  {
    deep: true,
  }
);

const getOptionsStr = (): string => {
  const optionItems = formStore.selectQuestion.optionItems;
  const itemList = optionItems?.map((item) => {
    return item.label;
  });
  return itemList.join("\n");
};

const getOptions = () => {
  const _items = items.value;
  if (isEmptyStr(_items)) {
    ElMessage.warning("枚举值不能为空");
    items.value = getOptionsStr();
    return;
  }
  const itemList = splitTextByEnter(_items);
  const temp = [];
  itemList?.forEach((item, index) => {
    if (item === "") return;
    temp.push({
      label: item,
      value: String(index + 1),
    });
  });
  // 判断是否修改
  let flag = false;
  const optionItems = formStore.selectQuestion.optionItems;
  if (optionItems.length !== temp.length) {
    formStore.selectQuestion.optionItems = temp;
    editQue(formStore.selectQuestion, formStore);
    return;
  }
  optionItems.forEach((item, index) => {
    if (item.label !== temp[index].label) {
      flag = true;
    }
  });
  flag && (formStore.selectQuestion.optionItems = temp);
  flag && editQue(formStore.selectQuestion, formStore);
};

items.value = getOptionsStr();
</script>
